package com.zero.demo.jms.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.MessageFormat;

/**
 * @author zengzr
 * @desc
 * @Date 2019/5/6 16:08
 */
@Log4j2
public class DynamicClassLoader extends ClassLoader {
    public DynamicClassLoader() {

    }

    public DynamicClassLoader(ClassLoader classLoader) {
        super(classLoader);
    }
    // 文件最后修改时间
    private long lastModified;

    // 加载class文件的classpath
    private String classPath;

    private boolean isClassModified(String name) {
        File file = getFile(name);
        if (file.lastModified() > lastModified) {
            return true;
        }
        return false;
    }

    public Class<?> loadClass(String classPath, String name)
            throws ClassNotFoundException {
        this.classPath = classPath;
        if (isClassModified(name)) {
            return findClass(name);
        }
        return null;
    }

    /**
     * 获取class文件的字节码
     *
     * @param name
     *            类的全名
     * @return
     */
    private byte[] getBytes(String name) {
        byte[] buffer = null;
        FileInputStream in = null;
        try {
            File file = getFile(name);
            lastModified = file.lastModified();
            in = new FileInputStream(file);
            buffer = new byte[in.available()];
            in.read(buffer);
            return buffer;
        } catch (FileNotFoundException e) {
            if (StringUtils.isNotEmpty(name) && (name.endsWith("Customizer") || name.endsWith("BeanInfo"))) {
                log.debug("动态脚本无Customizer和BeanInfo生成!!!"+e.getMessage() );
            }else{
                log.error(e.getMessage(),e);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer;
    }

    /**
     * 获取class文件的真实路径
     *
     * @param name
     * @return
     */
    private File getFile(String name) {
        String simpleName = "";
        String packageName = "";
        if (name.indexOf(".") != -1) {
            simpleName = name.substring(name.lastIndexOf(".") + 1);
            packageName = name.substring(0, name.lastIndexOf("."))
                    .replaceAll("[.]", "/");
        } else {
            simpleName = name;
        }
        File file = new File(MessageFormat.format("{0}/{1}/{2}.class",
                classPath, packageName, simpleName));
        return file;
    }

    @Override
    protected Class<?> findClass(String name) {
        Class<?> clazz = null;
        byte[] byteCode = getBytes(name);
        clazz = defineClass(null, byteCode, 0, byteCode.length);
        return clazz;
    }
}
